<template>
  <div class="security-incident-response">
    <el-card class="incident-response-card">
      <template #header>
        <div class="card-header">
          <h2>安全事件响应管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="openCreateIncidentDialog" icon="el-icon-plus">
              新建事件
            </el-button>
            <el-button @click="refreshIncidents" icon="el-icon-refresh">
              刷新
            </el-button>
            <el-dropdown @command="handleHeaderCommand">
              <el-button icon="el-icon-more">
                更多 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="exportIncidents">导出事件</el-dropdown-item>
                  <el-dropdown-item command="importIncidents">导入事件</el-dropdown-item>
                  <el-dropdown-item command="batchClose">批量关闭</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <!-- 仪表盘概览 -->
      <div class="dashboard-overview">
        <h3>事件概览</h3>
        <div class="stats-grid">
          <el-card class="stat-card critical">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-error"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ criticalCount }}</div>
                <div class="stat-label">严重事件</div>
              </div>
            </div>
          </el-card>
          <el-card class="stat-card high">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-warning"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ highCount }}</div>
                <div class="stat-label">高危事件</div>
              </div>
            </div>
          </el-card>
          <el-card class="stat-card medium">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-circle-check"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ mediumCount }}</div>
                <div class="stat-label">中危事件</div>
              </div>
            </div>
          </el-card>
          <el-card class="stat-card low">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-info"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ lowCount }}</div>
                <div class="stat-label">低危事件</div>
              </div>
            </div>
          </el-card>
          <el-card class="stat-card total">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ totalIncidents }}</div>
                <div class="stat-label">总事件数</div>
              </div>
            </div>
          </el-card>
          <el-card class="stat-card pending">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-time"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ pendingCount }}</div>
                <div class="stat-label">待处理事件</div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 事件趋势图表 -->
        <div class="charts-container">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>事件趋势 (近7天)</span>
                <el-select v-model="chartTimeRange" placeholder="选择时间范围" size="small">
                  <el-option label="近7天" value="7d"></el-option>
                  <el-option label="近30天" value="30d"></el-option>
                  <el-option label="近90天" value="90d"></el-option>
                </el-select>
              </div>
            </template>
            <div class="chart-content">
              <!-- 这里应该放置实际的图表组件 -->
              <div class="mock-chart line-chart">事件趋势图表占位</div>
            </div>
          </el-card>
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>事件类型分布</span>
              </div>
            </template>
            <div class="chart-content">
              <!-- 这里应该放置实际的图表组件 -->
              <div class="mock-chart pie-chart">事件类型分布图表占位</div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 搜索筛选区域 -->
      <div class="search-filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索事件ID、名称、描述"
              prefix-icon="el-icon-search"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="searchForm.severity"
              placeholder="选择严重级别"
              clearable
            >
              <el-option
                v-for="item in severityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="searchForm.type"
              placeholder="选择事件类型"
              clearable
            >
              <el-option
                v-for="item in incidentTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="handleSearch" icon="el-icon-search">
              搜索
            </el-button>
          </el-col>
        </el-row>
        
        <!-- 高级筛选 -->
        <div class="advanced-filter" v-if="showAdvancedFilter">
          <el-row :gutter="20" style="margin-top: 16px;">
            <el-col :span="8">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="searchForm.assignee"
                placeholder="处理人员"
                clearable
                filterable
              >
                <el-option
                  v-for="item in assignees"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="searchForm.source"
                placeholder="事件来源"
                clearable
              >
                <el-option
                  v-for="item in incidentSources"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-button @click="resetSearch">重置</el-button>
            </el-col>
          </el-row>
        </div>
        
        <div class="filter-actions">
          <el-button type="text" @click="toggleAdvancedFilter">
            {{ showAdvancedFilter ? '收起高级筛选' : '展开高级筛选' }}
            <i :class="['el-icon-arrow-down', { 'rotate-180': showAdvancedFilter }]"></i>
          </el-button>
        </div>
      </div>

      <!-- 事件列表 -->
      <div class="incidents-table">
        <el-table
          v-loading="loading"
          :data="incidentsData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="事件ID" width="120" />
          <el-table-column prop="title" label="事件名称" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="incident-title">
                <span class="title-text">{{ row.title }}</span>
                <el-tag 
                  v-if="isUrgent(row)" 
                  type="danger" 
                  size="small"
                  class="urgent-tag"
                >
                  紧急
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="severity" label="严重级别" width="100">
            <template #default="{ row }">
              <el-tag :type="getSeverityType(row.severity)">
                {{ getSeverityLabel(row.severity) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="事件类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getTypeType(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="90">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="source" label="来源" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getSourceLabel(row.source) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="detectedTime" label="发现时间" width="160" />
          <el-table-column prop="assignee" label="处理人员" width="100" />
          <el-table-column prop="responseTime" label="响应耗时" width="120">
            <template #default="{ row }">
              <span class="response-time" :class="getTimeClass(row.responseTime)">{{ row.responseTime || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="text" size="small" @click.stop="viewIncident(row.id)">查看</el-button>
              <el-button type="text" size="small" @click.stop="editIncident(row.id)">编辑</el-button>
              <el-dropdown @command="(command) => handleActionCommand(command, row.id)" trigger="click">
                <el-button type="text" size="small" @click.stop>
                  更多 <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="assign" v-if="row.status === 'open'">分配</el-dropdown-item>
                    <el-dropdown-item command="startProcess" v-if="row.status === 'open'">开始处理</el-dropdown-item>
                    <el-dropdown-item command="pauseProcess" v-if="row.status === 'processing'">暂停处理</el-dropdown-item>
                    <el-dropdown-item command="resolve" v-if="row.status !== 'resolved' && row.status !== 'closed'">标记已解决</el-dropdown-item>
                    <el-dropdown-item command="close" v-if="row.status === 'resolved'">关闭事件</el-dropdown-item>
                    <el-dropdown-item command="delete" danger>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑事件对话框 -->
    <el-dialog
      v-model="createIncidentDialogVisible"
      :title="isEditMode ? '编辑事件' : '新建事件'"
      width="80%"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="incidentFormRef"
        :model="incidentForm"
        :rules="incidentFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="事件名称" prop="title">
              <el-input v-model="incidentForm.title" placeholder="请输入事件名称" />
            </el-form-item>
            <el-form-item label="事件描述" prop="description">
              <el-input
                v-model="incidentForm.description"
                type="textarea"
                rows="4"
                placeholder="请详细描述事件情况"
              />
            </el-form-item>
            <el-form-item label="影响范围" prop="impactScope">
              <el-input
                v-model="incidentForm.impactScope"
                type="textarea"
                rows="2"
                placeholder="请描述事件影响的系统、数据或服务"
              />
            </el-form-item>
            <el-form-item label="详细分析" prop="analysis">
              <el-input
                v-model="incidentForm.analysis"
                type="textarea"
                rows="6"
                placeholder="请输入事件详细分析内容"
              />
            </el-form-item>
            <el-form-item label="解决方案" prop="solution">
              <el-input
                v-model="incidentForm.solution"
                type="textarea"
                rows="4"
                placeholder="请输入解决方案"
              />
            </el-form-item>
            <el-form-item label="预防措施" prop="preventionMeasures">
              <el-input
                v-model="incidentForm.preventionMeasures"
                type="textarea"
                rows="3"
                placeholder="请输入预防类似事件的措施"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="form-sidebar">
              <el-form-item label="严重级别" prop="severity">
                <el-select v-model="incidentForm.severity" placeholder="选择严重级别">
                  <el-option
                    v-for="item in severityOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="事件类型" prop="type">
                <el-select v-model="incidentForm.type" placeholder="选择事件类型">
                  <el-option
                    v-for="item in incidentTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="事件来源" prop="source">
                <el-select v-model="incidentForm.source" placeholder="选择事件来源">
                  <el-option
                    v-for="item in incidentSources"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="发现时间" prop="detectedTime">
                <el-date-picker
                  v-model="incidentForm.detectedTime"
                  type="datetime"
                  placeholder="选择发现时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="处理人员" prop="assignee">
                <el-select v-model="incidentForm.assignee" placeholder="选择处理人员" clearable filterable>
                  <el-option
                    v-for="item in assignees"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="incidentForm.status" placeholder="选择状态">
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="优先级" prop="priority">
                <el-select v-model="incidentForm.priority" placeholder="选择优先级">
                  <el-option label="P1-最高" value="p1" />
                  <el-option label="P2-高" value="p2" />
                  <el-option label="P3-中" value="p3" />
                  <el-option label="P4-低" value="p4" />
                </el-select>
              </el-form-item>
              <el-form-item label="关联资产" prop="relatedAssets">
                <el-select
                  v-model="incidentForm.relatedAssets"
                  placeholder="选择关联资产"
                  multiple
                  filterable
                >
                  <el-option
                    v-for="item in assets"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="关联漏洞" prop="relatedVulnerabilities">
                <el-input
                  v-model="incidentForm.relatedVulnerabilities"
                  placeholder="请输入关联漏洞ID，逗号分隔"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitIncidentForm">提交</el-button>
                <el-button @click="handleDialogClose">取消</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 事件详情对话框 -->
    <el-dialog
      v-model="incidentDetailDialogVisible"
      :title="currentIncident.title || '事件详情'"
      width="90%"
      :close-on-click-modal="false"
      @close="closeIncidentDetail"
    >
      <div class="incident-detail">
        <div class="detail-header">
          <div class="basic-info">
            <h2>{{ currentIncident.title }}</h2>
            <div class="incident-meta">
              <el-tag :type="getSeverityType(currentIncident.severity)">
                {{ getSeverityLabel(currentIncident.severity) }}
              </el-tag>
              <el-tag :type="getStatusType(currentIncident.status)">
                {{ getStatusLabel(currentIncident.status) }}
              </el-tag>
              <el-tag size="small">{{ getTypeLabel(currentIncident.type) }}</el-tag>
              <span class="incident-id">#{{ currentIncident.id }}</span>
            </div>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="editIncident(currentIncident.id)">编辑</el-button>
            <el-dropdown @command="(command) => handleDetailActionCommand(command, currentIncident)">
              <el-button>更多操作</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="assign" v-if="currentIncident.status === 'open'">分配给</el-dropdown-item>
                  <el-dropdown-item command="startProcess" v-if="currentIncident.status === 'open'">开始处理</el-dropdown-item>
                  <el-dropdown-item command="resolve" v-if="currentIncident.status !== 'resolved' && currentIncident.status !== 'closed'">标记已解决</el-dropdown-item>
                  <el-dropdown-item command="close" v-if="currentIncident.status === 'resolved'">关闭事件</el-dropdown-item>
                  <el-dropdown-item command="addComment">添加评论</el-dropdown-item>
                  <el-dropdown-item command="exportPDF">导出PDF</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <div class="detail-content">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="事件ID">{{ currentIncident.id }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ currentIncident.createTime }}</el-descriptions-item>
                <el-descriptions-item label="发现时间">{{ currentIncident.detectedTime }}</el-descriptions-item>
                <el-descriptions-item label="最后更新">{{ currentIncident.lastUpdate }}</el-descriptions-item>
                <el-descriptions-item label="处理人员">{{ currentIncident.assignee || '未分配' }}</el-descriptions-item>
                <el-descriptions-item label="优先级">{{ getPriorityLabel(currentIncident.priority) }}</el-descriptions-item>
                <el-descriptions-item label="事件来源">{{ getSourceLabel(currentIncident.source) }}</el-descriptions-item>
                <el-descriptions-item label="响应耗时">{{ currentIncident.responseTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="影响范围" :span="2">{{ currentIncident.impactScope || '-' }}</el-descriptions-item>
                <el-descriptions-item label="关联资产" :span="2">
                  <el-tag 
                    v-for="asset in (currentIncident.relatedAssets || [])" 
                    :key="asset" 
                    size="small" 
                    class="mr-1"
                  >
                    {{ asset }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="关联漏洞" :span="2">{{ currentIncident.relatedVulnerabilities || '-' }}</el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>
            
            <el-tab-pane label="事件描述">
              <div class="description-content">
                {{ currentIncident.description || '-' }}
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="详细分析">
              <div class="analysis-content">
                {{ currentIncident.analysis || '-' }}
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="解决方案">
              <div class="solution-content">
                {{ currentIncident.solution || '-' }}
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="时间线">
              <div class="timeline-container">
                <el-timeline>
                  <el-timeline-item 
                    v-for="(event, index) in currentIncident.timeline || []" 
                    :key="index"
                    :timestamp="event.time"
                    :type="getTimelineType(event.type)"
                  >
                    <div class="timeline-content">
                      <div class="timeline-title">{{ event.title }}</div>
                      <div class="timeline-desc">{{ event.description }}</div>
                      <div class="timeline-author">{{ event.author || '系统' }}</div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="评论">
              <div class="comments-container">
                <div v-for="(comment, index) in currentIncident.comments || []" :key="index" class="comment-item">
                  <div class="comment-header">
                    <span class="comment-author">{{ comment.author }}</span>
                    <span class="comment-time">{{ comment.time }}</span>
                  </div>
                  <div class="comment-content">{{ comment.content }}</div>
                </div>
                
                <div class="add-comment">
                  <el-input
                    v-model="newComment"
                    type="textarea"
                    rows="3"
                    placeholder="添加评论..."
                  />
                  <div class="comment-actions">
                    <el-button type="primary" @click="submitComment">提交评论</el-button>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-dialog>

    <!-- 分配事件对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配事件"
      width="400px"
      :close-on-click-modal="false"
      @close="closeAssignDialog"
    >
      <el-form ref="assignFormRef" :model="assignForm" label-width="80px">
        <el-form-item label="处理人员" prop="assignee">
          <el-select v-model="assignForm.assignee" placeholder="选择处理人员" filterable>
            <el-option
              v-for="item in assignees"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="assignForm.note"
            type="textarea"
            rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAssignForm">确定分配</el-button>
          <el-button @click="closeAssignDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 批量操作对话框 -->
    <el-dialog
      v-model="batchActionDialogVisible"
      :title="batchActionTitle"
      width="500px"
      :close-on-click-modal="false"
      @close="closeBatchActionDialog"
    >
      <el-form ref="batchActionFormRef" :model="batchActionForm" label-width="100px">
        <template v-if="batchActionType === 'assign'">
          <el-form-item label="处理人员" prop="assignee">
            <el-select v-model="batchActionForm.assignee" placeholder="选择处理人员" filterable>
              <el-option
                v-for="item in assignees"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-else-if="batchActionType === 'updateStatus'">
          <el-form-item label="更新状态" prop="status">
            <el-select v-model="batchActionForm.status" placeholder="选择状态">
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-else-if="batchActionType === 'updateSeverity'">
          <el-form-item label="更新严重级别" prop="severity">
            <el-select v-model="batchActionForm.severity" placeholder="选择严重级别">
              <el-option
                v-for="item in severityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="备注">
          <el-input
            v-model="batchActionForm.note"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitBatchActionForm">确定</el-button>
          <el-button @click="closeBatchActionDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加评论对话框 -->
    <el-dialog
      v-model="addCommentDialogVisible"
      title="添加评论"
      width="500px"
      :close-on-click-modal="false"
      @close="closeAddCommentDialog"
    >
      <el-form ref="commentFormRef" :model="commentForm" label-width="80px">
        <el-form-item label="评论内容" prop="content">
          <el-input
            v-model="commentForm.content"
            type="textarea"
            rows="6"
            placeholder="请输入评论内容"
          />
        </el-form-item>
        <el-form-item label="附件" prop="attachments">
          <el-upload
            class="upload-demo"
            drag
            action=""
            :before-upload="handleCommentFileUpload"
            multiple
            :file-list="commentForm.attachments"
            :auto-upload="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                支持上传图片、文档等附件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitCommentForm">提交评论</el-button>
          <el-button @click="closeAddCommentDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import '../assets/compliance-style.css' // 复用样式文件

// 响应式数据
const loading = ref(false)
const showAdvancedFilter = ref(false)
const dateRange = ref([])
const selectedIncidents = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const isEditMode = ref(false)
const chartTimeRange = ref('7d')

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  severity: '',
  type: '',
  assignee: '',
  source: ''
})

// 事件表单
const incidentForm = reactive({
  id: '',
  title: '',
  description: '',
  analysis: '',
  solution: '',
  preventionMeasures: '',
  impactScope: '',
  severity: '',
  type: '',
  status: 'open',
  source: '',
  detectedTime: '',
  assignee: '',
  priority: 'p3',
  relatedAssets: [],
  relatedVulnerabilities: ''
})

// 分配表单
const assignForm = reactive({
  assignee: '',
  note: ''
})

// 批量操作表单
const batchActionForm = reactive({
  assignee: '',
  status: '',
  severity: '',
  note: ''
})

// 评论表单
const commentForm = reactive({
  content: '',
  attachments: []
})

// 对话框状态
const createIncidentDialogVisible = ref(false)
const incidentDetailDialogVisible = ref(false)
const assignDialogVisible = ref(false)
const batchActionDialogVisible = ref(false)
const addCommentDialogVisible = ref(false)

// 表单引用
const incidentFormRef = ref(null)
const assignFormRef = ref(null)
const batchActionFormRef = ref(null)
const commentFormRef = ref(null)

// 当前事件
const currentIncident = ref({})
const newComment = ref('')
const activeTab = ref('0')
const batchActionType = ref('')
const batchActionTitle = ref('')

// 事件列表数据
const incidents = ref([])

// 状态选项
const statusOptions = ref([
  { value: 'open', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'resolved', label: '已解决' },
  { value: 'closed', label: '已关闭' }
])

// 严重级别选项
const severityOptions = ref([
  { value: 'critical', label: '严重' },
  { value: 'high', label: '高危' },
  { value: 'medium', label: '中危' },
  { value: 'low', label: '低危' }
])

// 事件类型
const incidentTypes = ref([
  { value: 'data_breach', label: '数据泄露' },
  { value: 'ransomware', label: '勒索软件' },
  { value: 'malware', label: '恶意软件' },
  { value: 'phishing', label: '钓鱼攻击' },
  { value: 'ddos', label: 'DDoS攻击' },
  { value: 'unauthorized_access', label: '未授权访问' },
  { value: 'vulnerability_exploit', label: '漏洞利用' },
  { value: 'insider_threat', label: '内部威胁' },
  { value: 'misconfiguration', label: '配置错误' },
  { value: 'other', label: '其他' }
])

// 事件来源
const incidentSources = ref([
  { value: 'ids_ips', label: 'IDS/IPS' },
  { value: 'siem', label: 'SIEM' },
  { value: 'edr', label: 'EDR' },
  { value: 'vuln_scanner', label: '漏洞扫描器' },
  { value: 'manual', label: '人工发现' },
  { value: 'user_report', label: '用户报告' },
  { value: 'third_party', label: '第三方通知' },
  { value: 'other', label: '其他' }
])

// 处理人员列表
const assignees = ref(['张三', '李四', '王五', '赵六', '安全团队', '系统管理员'])

// 资产列表
const assets = ref(['Web服务器-01', '数据库服务器-02', '应用服务器-03', '邮件服务器-04', '防火墙', 'VPN设备', '负载均衡器'])

// 表单验证规则
const incidentFormRules = {
  title: [
    { required: true, message: '请输入事件名称', trigger: 'blur' },
    { min: 5, max: 200, message: '事件名称长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入事件描述', trigger: 'blur' }
  ],
  severity: [
    { required: true, message: '请选择严重级别', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择事件类型', trigger: 'change' }
  ],
  source: [
    { required: true, message: '请选择事件来源', trigger: 'change' }
  ],
  detectedTime: [
    { required: true, message: '请选择发现时间', trigger: 'change' }
  ]
}

// 计算属性
const totalIncidents = computed(() => incidents.value.length)
const criticalCount = computed(() => incidents.value.filter(incident => incident.severity === 'critical').length)
const highCount = computed(() => incidents.value.filter(incident => incident.severity === 'high').length)
const mediumCount = computed(() => incidents.value.filter(incident => incident.severity === 'medium').length)
const lowCount = computed(() => incidents.value.filter(incident => incident.severity === 'low').length)
const pendingCount = computed(() => incidents.value.filter(incident => incident.status === 'open' || incident.status === 'processing').length)

const incidentsData = computed(() => {
  // 这里应该根据筛选条件过滤数据，现在返回所有数据作为演示
  return incidents.value
})

// 辅助函数
const getSeverityLabel = (severity) => {
  const labelMap = {
    'critical': '严重',
    'high': '高危',
    'medium': '中危',
    'low': '低危'
  }
  return labelMap[severity] || '未知'
}

const getSeverityType = (severity) => {
  const typeMap = {
    'critical': 'danger',
    'high': 'danger',
    'medium': 'warning',
    'low': 'info'
  }
  return typeMap[severity] || 'info'
}

const getStatusLabel = (status) => {
  const labelMap = {
    'open': '待处理',
    'processing': '处理中',
    'resolved': '已解决',
    'closed': '已关闭'
  }
  return labelMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    'open': 'info',
    'processing': 'warning',
    'resolved': 'success',
    'closed': 'success'
  }
  return typeMap[status] || 'info'
}

const getTypeLabel = (type) => {
  const typeObj = incidentTypes.value.find(item => item.value === type)
  return typeObj ? typeObj.label : '未知'
}

const getTypeType = (type) => {
  const typeMap = {
    'data_breach': 'danger',
    'ransomware': 'danger',
    'malware': 'warning',
    'phishing': 'warning',
    'ddos': 'warning',
    'unauthorized_access': 'danger',
    'vulnerability_exploit': 'warning',
    'insider_threat': 'danger',
    'misconfiguration': 'info',
    'other': 'info'
  }
  return typeMap[type] || 'info'
}

const getSourceLabel = (source) => {
  const sourceObj = incidentSources.value.find(item => item.value === source)
  return sourceObj ? sourceObj.label : '未知'
}

const getPriorityLabel = (priority) => {
  const labelMap = {
    'p1': 'P1-最高',
    'p2': 'P2-高',
    'p3': 'P3-中',
    'p4': 'P4-低'
  }
  return labelMap[priority] || '未知'
}

const getTimelineType = (type) => {
  const typeMap = {
    'create': 'primary',
    'assign': 'info',
    'process': 'warning',
    'resolve': 'success',
    'close': 'success',
    'comment': 'info',
    'update': 'info'
  }
  return typeMap[type] || 'primary'
}

const isUrgent = (incident) => {
  // 判断是否为紧急事件：严重级别为critical且状态为open或processing
  return incident.severity === 'critical' && (incident.status === 'open' || incident.status === 'processing')
}

const getTimeClass = (timeStr) => {
  if (!timeStr) return ''
  // 简单的时间判断逻辑，实际项目中应根据具体需求实现
  if (timeStr.includes('小时') && parseInt(timeStr) > 24) {
    return 'time-warning'
  }
  if (timeStr.includes('天')) {
    return 'time-danger'
  }
  return 'time-normal'
}

// 模拟数据
const generateMockData = () => {
  const mockIncidents = [
    {
      id: 'INC-20240115-001',
      title: 'Web服务器遭受SQL注入攻击',
      description: '监控系统发现Web服务器存在异常SQL查询，疑似遭受SQL注入攻击。',
      analysis: '经分析，攻击者利用应用程序中未过滤的用户输入参数，向数据库发送恶意SQL语句。攻击尝试获取用户敏感信息。',
      solution: '1. 修补应用程序中的SQL注入漏洞\n2. 实施参数化查询\n3. 部署WAF规则拦截类似攻击\n4. 重置可能泄露的用户凭证',
      preventionMeasures: '1. 加强代码审查，确保所有用户输入经过验证和过滤\n2. 实施最小权限原则\n3. 定期进行安全测试',
      impactScope: '用户数据库，可能泄露用户个人信息和凭证',
      severity: 'critical',
      type: 'vulnerability_exploit',
      status: 'processing',
      source: 'ids_ips',
      detectedTime: '2024-01-15 08:30:00',
      createTime: '2024-01-15 08:35:00',
      lastUpdate: '2024-01-15 10:20:00',
      assignee: '张三',
      priority: 'p1',
      responseTime: '1小时50分钟',
      relatedAssets: ['Web服务器-01', '数据库服务器-02'],
      relatedVulnerabilities: 'CVE-2023-25136',
      timeline: [
        { time: '2024-01-15 08:35:00', type: 'create', title: '事件创建', description: '系统自动创建事件', author: '系统' },
        { time: '2024-01-15 08:40:00', type: 'assign', title: '分配给张三', description: '事件分配给安全分析师张三', author: '李四' },
        { time: '2024-01-15 09:00:00', type: 'process', title: '开始处理', description: '张三开始分析和处理此事件', author: '张三' },
        { time: '2024-01-15 10:20:00', type: 'update', title: '更新分析结果', description: '张三更新了事件分析结果', author: '张三' }
      ],
      comments: [
        { author: '张三', time: '2024-01-15 09:15:00', content: '已确认SQL注入漏洞存在，正在准备修复方案。' },
        { author: '李四', time: '2024-01-15 10:00:00', content: '请优先处理，此服务器包含重要业务数据。' }
      ]
    },
    {
      id: 'INC-20240114-002',
      title: '员工收到钓鱼邮件',
      description: '多名员工报告收到伪装成IT部门的钓鱼邮件，试图获取员工凭证。',
      analysis: '邮件伪装成IT部门密码重置通知，包含恶意链接。经检查，链接指向仿冒的公司登录页面。',
      solution: '1. 向全体员工发送安全警报\n2. 阻断恶意域名\n3. 强制重置可能点击链接的员工密码\n4. 加强钓鱼邮件防护规则',
      preventionMeasures: '1. 加强员工安全意识培训\n2. 实施DMARC、SPF和DKIM邮件认证\n3. 部署高级邮件安全网关',
      impactScope: '全体员工，可能导致账户被盗用',
      severity: 'high',
      type: 'phishing',
      status: 'resolved',
      source: 'user_report',
      detectedTime: '2024-01-14 14:20:00',
      createTime: '2024-01-14 14:30:00',
      lastUpdate: '2024-01-14 16:45:00',
      assignee: '李四',
      priority: 'p2',
      responseTime: '2小时15分钟',
      relatedAssets: [],
      relatedVulnerabilities: '',
      timeline: [
        { time: '2024-01-14 14:30:00', type: 'create', title: '事件创建', description: '安全团队创建事件', author: '王五' },
        { time: '2024-01-14 14:35:00', type: 'assign', title: '分配给李四', description: '事件分配给安全响应专员李四', author: '王五' },
        { time: '2024-01-14 14:40:00', type: 'process', title: '开始处理', description: '李四开始处理钓鱼邮件事件', author: '李四' },
        { time: '2024-01-14 16:30:00', type: 'update', title: '实施防护措施', description: '已阻断恶意域名并发送安全警报', author: '李四' },
        { time: '2024-01-14 16:45:00', type: 'resolve', title: '标记已解决', description: '事件已解决，已实施防护措施', author: '李四' }
      ],
      comments: [
        { author: '李四', time: '2024-01-14 15:00:00', content: '已确认是钓鱼邮件，正在分析邮件头信息溯源。' },
        { author: '王五', time: '2024-01-14 15:30:00', content: '请尽快发送公司范围内的安全警报。' }
      ]
    },
    {
      id: 'INC-20240113-003',
      title: '服务器配置错误导致信息泄露',
      description: '安全扫描发现Web服务器配置不当，导致敏感目录可被未授权访问。',
      analysis: '服务器的.htaccess配置存在错误，导致某些包含敏感信息的目录未被正确保护。攻击者可能访问到配置文件和日志。',
      solution: '1. 修复.htaccess配置\n2. 审查并移除敏感文件\n3. 加强目录访问控制\n4. 更新Web服务器安全基线',
      preventionMeasures: '1. 实施配置管理系统\n2. 定期进行配置审计\n3. 使用自动化工具检测配置错误',
      impactScope: 'Web服务器配置信息，可能包含数据库连接字符串等敏感信息',
      severity: 'medium',
      type: 'misconfiguration',
      status: 'closed',
      source: 'vuln_scanner',
      detectedTime: '2024-01-13 09:45:00',
      createTime: '2024-01-13 10:00:00',
      lastUpdate: '2024-01-13 15:30:00',
      assignee: '赵六',
      priority: 'p3',
      responseTime: '5小时30分钟',
      relatedAssets: ['Web服务器-01'],
      relatedVulnerabilities: '',
      timeline: [
        { time: '2024-01-13 10:00:00', type: 'create', title: '事件创建', description: '漏洞扫描器自动创建事件', author: '系统' },
        { time: '2024-01-13 10:15:00', type: 'assign', title: '分配给赵六', description: '事件分配给系统管理员赵六', author: '王五' },
        { time: '2024-01-13 10:30:00', type: 'process', title: '开始处理', description: '赵六开始修复配置错误', author: '赵六' },
        { time: '2024-01-13 14:00:00', type: 'update', title: '修复完成', description: '已修复.htaccess配置问题', author: '赵六' },
        { time: '2024-01-13 14:30:00', type: 'resolve', title: '标记已解决', description: '配置问题已解决，验证通过', author: '赵六' },
        { time: '2024-01-13 15:30:00', type: 'close', title: '关闭事件', description: '事件已完全处理并关闭', author: '王五' }
      ],
      comments: [
        { author: '赵六', time: '2024-01-13 10:45:00', content: '已找到配置问题，正在修复。' },
        { author: '王五', time: '2024-01-13 15:00:00', content: '请确保更新配置管理系统中的基线标准。' }
      ]
    },
    {
      id: 'INC-20240112-004',
      title: '可疑网络流量检测',
      description: '网络监控系统检测到服务器与已知恶意IP地址之间的通信。',
      analysis: '某应用服务器向外部恶意IP地址发送了异常流量，疑似数据外泄或命令控制通信。',
      solution: '1. 隔离受影响服务器\n2. 分析流量内容和来源\n3. 检查服务器是否被入侵\n4. 实施网络隔离措施',
      preventionMeasures: '1. 实施网络分段\n2. 加强出站流量监控\n3. 部署网络行为分析工具',
      impactScope: '应用服务器，可能导致数据泄露或系统被控制',
      severity: 'high',
      type: 'unauthorized_access',
      status: 'open',
      source: 'siem',
      detectedTime: '2024-01-12 20:15:00',
      createTime: '2024-01-12 20:30:00',
      lastUpdate: '2024-01-12 20:30:00',
      assignee: '',
      priority: 'p2',
      responseTime: '',
      relatedAssets: ['应用服务器-03'],
      relatedVulnerabilities: '',
      timeline: [
        { time: '2024-01-12 20:30:00', type: 'create', title: '事件创建', description: 'SIEM系统自动创建事件', author: '系统' }
      ],
      comments: []
    },
    {
      id: 'INC-20240111-005',
      title: '终端检测到恶意软件',
      description: 'EDR系统在多台终端上检测到勒索软件变种。',
      analysis: '员工通过USB设备或邮件附件引入了勒索软件，已在多台终端上发现感染迹象。',
      solution: '1. 隔离受感染终端\n2. 终止恶意进程并删除恶意文件\n3. 从备份恢复受影响数据\n4. 重置用户账户密码',
      preventionMeasures: '1. 加强终端防护\n2. 限制USB设备使用\n3. 实施应用白名单\n4. 加强员工安全培训',
      impactScope: '多台员工终端，部分数据可能被加密',
      severity: 'critical',
      type: 'ransomware',
      status: 'processing',
      source: 'edr',
      detectedTime: '2024-01-11 16:45:00',
      createTime: '2024-01-11 17:00:00',
      lastUpdate: '2024-01-12 09:15:00',
      assignee: '安全团队',
      priority: 'p1',
      responseTime: '15小时15分钟',
      relatedAssets: [],
      relatedVulnerabilities: '',
      timeline: [
        { time: '2024-01-11 17:00:00', type: 'create', title: '事件创建', description: 'EDR系统自动创建事件', author: '系统' },
        { time: '2024-01-11 17:15:00', type: 'assign', title: '分配给安全团队', description: '事件分配给安全应急响应团队', author: '王五' },
        { time: '2024-01-11 17:30:00', type: 'process', title: '启动应急响应', description: '安全团队启动勒索软件应急响应流程', author: '安全团队' },
        { time: '2024-01-12 09:15:00', type: 'update', title: '更新处理进展', description: '已隔离大部分受感染终端，正在进行清除工作', author: '安全团队' }
      ],
      comments: [
        { author: '安全团队', time: '2024-01-11 18:00:00', content: '已确认是新型勒索软件，正在制定清除方案。' },
        { author: '王五', time: '2024-01-11 20:30:00', content: '请及时向管理层汇报事件进展。' }
      ]
    }
  ]
  
  incidents.value = mockIncidents
  total.value = mockIncidents.length
}

// 方法函数
const fetchIncidents = async () => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.getIncidents({ ...searchForm, page: currentPage.value, pageSize: pageSize.value })
    // incidents.value = response.data
    // total.value = response.total
    
    // 使用模拟数据
    generateMockData()
  } catch (error) {
    ElMessage.error('获取事件列表失败')
    console.error('Failed to fetch incidents:', error)
  } finally {
    loading.value = false
  }
}

const fetchIncidentDetail = async (incidentId) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.getIncidentDetail(incidentId)
    // currentIncident.value = response
    
    // 从模拟数据中查找
    currentIncident.value = incidents.value.find(incident => incident.id === incidentId)
  } catch (error) {
    ElMessage.error('获取事件详情失败')
    console.error('Failed to fetch incident detail:', error)
  } finally {
    loading.value = false
  }
}

const createIncident = async (formData) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.createIncident(formData)
    
    // 添加到模拟数据
    const newIncident = {
      ...formData,
      id: `INC-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-${String(incidents.value.length + 1).padStart(3, '0')}`,
      createTime: new Date().toLocaleString('zh-CN'),
      lastUpdate: new Date().toLocaleString('zh-CN'),
      timeline: [
        { 
          time: new Date().toLocaleString('zh-CN'), 
          type: 'create', 
          title: '事件创建', 
          description: '手动创建事件', 
          author: '当前用户' 
        }
      ],
      comments: []
    }
    
    incidents.value.unshift(newIncident)
    total.value += 1
    
    ElMessage.success('事件创建成功')
  } catch (error) {
    ElMessage.error('事件创建失败')
    console.error('Failed to create incident:', error)
  } finally {
    loading.value = false
  }
}

const updateIncident = async (formData) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.updateIncident(formData.id, formData)
    
    // 更新模拟数据
    const index = incidents.value.findIndex(incident => incident.id === formData.id)
    if (index !== -1) {
      // 保存原始数据用于比较
      const originalIncident = { ...incidents.value[index] }
      
      // 更新事件数据
      incidents.value[index] = {
        ...incidents.value[index],
        ...formData,
        lastUpdate: new Date().toLocaleString('zh-CN')
      }
      
      // 添加时间线记录
      if (incidents.value[index].timeline) {
        incidents.value[index].timeline.push({
          time: new Date().toLocaleString('zh-CN'),
          type: 'update',
          title: '事件更新',
          description: '事件信息已更新',
          author: '当前用户'
        })
      }
    }
    
    ElMessage.success('事件更新成功')
  } catch (error) {
    ElMessage.error('事件更新失败')
    console.error('Failed to update incident:', error)
  } finally {
    loading.value = false
  }
}

const deleteIncident = async (incidentId) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.deleteIncident(incidentId)
    
    // 从模拟数据中删除
    const index = incidents.value.findIndex(incident => incident.id === incidentId)
    if (index !== -1) {
      incidents.value.splice(index, 1)
      total.value -= 1
    }
    
    ElMessage.success('事件删除成功')
  } catch (error) {
    ElMessage.error('事件删除失败')
    console.error('Failed to delete incident:', error)
  } finally {
    loading.value = false
  }
}

const assignIncident = async (incidentId, assignee, note = '') => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.assignIncident(incidentId, { assignee, note })
    
    // 更新模拟数据
    const incident = incidents.value.find(inc => inc.id === incidentId)
    if (incident) {
      incident.assignee = assignee
      incident.lastUpdate = new Date().toLocaleString('zh-CN')
      
      // 添加时间线记录
      if (incident.timeline) {
        incident.timeline.push({
          time: new Date().toLocaleString('zh-CN'),
          type: 'assign',
          title: `分配给${assignee}`,
          description: note || '事件分配给新的处理人员',
          author: '当前用户'
        })
      }
    }
    
    ElMessage.success('事件分配成功')
  } catch (error) {
    ElMessage.error('事件分配失败')
    console.error('Failed to assign incident:', error)
  } finally {
    loading.value = false
  }
}

const updateIncidentStatus = async (incidentId, status, note = '') => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.updateIncidentStatus(incidentId, { status, note })
    
    // 更新模拟数据
    const incident = incidents.value.find(inc => inc.id === incidentId)
    if (incident) {
      incident.status = status
      incident.lastUpdate = new Date().toLocaleString('zh-CN')
      
      // 计算响应时间（如果从open变为processing）
      if (status === 'processing' && incident.status === 'open') {
        const detectedTime = new Date(incident.detectedTime)
        const now = new Date()
        const diffMs = now - detectedTime
        const diffMins = Math.floor(diffMs / 60000)
        const diffHours = Math.floor(diffMins / 60)
        const remainingMins = diffMins % 60
        incident.responseTime = `${diffHours}小时${remainingMins}分钟`
      }
      
      // 添加时间线记录
      let actionTitle = ''
      switch (status) {
        case 'processing':
          actionTitle = '开始处理'
          break
        case 'resolved':
          actionTitle = '标记已解决'
          break
        case 'closed':
          actionTitle = '关闭事件'
          break
      }
      
      if (actionTitle && incident.timeline) {
        incident.timeline.push({
          time: new Date().toLocaleString('zh-CN'),
          type: status === 'processing' ? 'process' : status,
          title: actionTitle,
          description: note || `事件状态变更为${getStatusLabel(status)}`,
          author: '当前用户'
        })
      }
    }
    
    ElMessage.success('事件状态更新成功')
  } catch (error) {
    ElMessage.error('事件状态更新失败')
    console.error('Failed to update incident status:', error)
  } finally {
    loading.value = false
  }
}

const addCommentToIncident = async (incidentId, comment, attachments = []) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.addComment(incidentId, { content: comment, attachments })
    
    // 更新模拟数据
    const incident = incidents.value.find(inc => inc.id === incidentId)
    if (incident) {
      if (!incident.comments) {
        incident.comments = []
      }
      
      incident.comments.push({
        author: '当前用户',
        time: new Date().toLocaleString('zh-CN'),
        content: comment
      })
      
      incident.lastUpdate = new Date().toLocaleString('zh-CN')
      
      // 添加时间线记录
      if (incident.timeline) {
        incident.timeline.push({
          time: new Date().toLocaleString('zh-CN'),
          type: 'comment',
          title: '添加评论',
          description: '用户添加了新的评论',
          author: '当前用户'
        })
      }
    }
    
    ElMessage.success('评论添加成功')
  } catch (error) {
    ElMessage.error('评论添加失败')
    console.error('Failed to add comment:', error)
  } finally {
    loading.value = false
  }
}

const batchAssignIncidents = async (incidentIds, assignee, note = '') => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.batchAssignIncidents(incidentIds, { assignee, note })
    
    // 更新模拟数据
    incidentIds.forEach(id => {
      const incident = incidents.value.find(inc => inc.id === id)
      if (incident) {
        incident.assignee = assignee
        incident.lastUpdate = new Date().toLocaleString('zh-CN')
        
        // 添加时间线记录
        if (incident.timeline) {
          incident.timeline.push({
            time: new Date().toLocaleString('zh-CN'),
            type: 'assign',
            title: `批量分配给${assignee}`,
            description: note || '事件通过批量操作分配给新的处理人员',
            author: '当前用户'
          })
        }
      }
    })
    
    ElMessage.success(`成功分配${incidentIds.length}个事件`)
  } catch (error) {
    ElMessage.error('批量分配失败')
    console.error('Failed to batch assign incidents:', error)
  } finally {
    loading.value = false
  }
}

const batchUpdateIncidentStatus = async (incidentIds, status, note = '') => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.batchUpdateIncidentStatus(incidentIds, { status, note })
    
    // 更新模拟数据
    incidentIds.forEach(id => {
      const incident = incidents.value.find(inc => inc.id === id)
      if (incident) {
        incident.status = status
        incident.lastUpdate = new Date().toLocaleString('zh-CN')
        
        // 添加时间线记录
        let actionTitle = ''
        switch (status) {
          case 'processing':
            actionTitle = '开始处理'
            break
          case 'resolved':
            actionTitle = '标记已解决'
            break
          case 'closed':
            actionTitle = '关闭事件'
            break
        }
        
        if (actionTitle && incident.timeline) {
          incident.timeline.push({
            time: new Date().toLocaleString('zh-CN'),
            type: status === 'processing' ? 'process' : status,
            title: `批量${actionTitle}`,
            description: note || `事件通过批量操作状态变更为${getStatusLabel(status)}`,
            author: '当前用户'
          })
        }
      }
    })
    
    ElMessage.success(`成功更新${incidentIds.length}个事件状态`)
  } catch (error) {
    ElMessage.error('批量更新状态失败')
    console.error('Failed to batch update incident status:', error)
  } finally {
    loading.value = false
  }
}

const batchUpdateIncidentSeverity = async (incidentIds, severity, note = '') => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.batchUpdateIncidentSeverity(incidentIds, { severity, note })
    
    // 更新模拟数据
    incidentIds.forEach(id => {
      const incident = incidents.value.find(inc => inc.id === id)
      if (incident) {
        incident.severity = severity
        incident.lastUpdate = new Date().toLocaleString('zh-CN')
        
        // 添加时间线记录
        if (incident.timeline) {
          incident.timeline.push({
            time: new Date().toLocaleString('zh-CN'),
            type: 'update',
            title: '批量更新严重级别',
            description: note || `事件严重级别通过批量操作变更为${getSeverityLabel(severity)}`,
            author: '当前用户'
          })
        }
      }
    })
    
    ElMessage.success(`成功更新${incidentIds.length}个事件严重级别`)
  } catch (error) {
    ElMessage.error('批量更新严重级别失败')
    console.error('Failed to batch update incident severity:', error)
  } finally {
    loading.value = false
  }
}

const batchDeleteIncidents = async (incidentIds) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.batchDeleteIncidents(incidentIds)
    
    // 从模拟数据中删除
    incidentIds.forEach(id => {
      const index = incidents.value.findIndex(incident => incident.id === id)
      if (index !== -1) {
        incidents.value.splice(index, 1)
      }
    })
    
    total.value -= incidentIds.length
    ElMessage.success(`成功删除${incidentIds.length}个事件`)
  } catch (error) {
    ElMessage.error('批量删除失败')
    console.error('Failed to batch delete incidents:', error)
  } finally {
    loading.value = false
  }
}

const exportIncidents = async () => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.exportIncidents(searchForm)
    
    // 模拟导出功能
    ElMessage.success('导出成功，请在下载中心查看')
  } catch (error) {
    ElMessage.error('导出失败')
    console.error('Failed to export incidents:', error)
  } finally {
    loading.value = false
  }
}

// 事件处理函数
const handleSearch = () => {
  currentPage.value = 1
  fetchIncidents()
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  dateRange.value = []
  fetchIncidents()
}

const toggleAdvancedFilter = () => {
  showAdvancedFilter.value = !showAdvancedFilter.value
}

const handleSelectionChange = (selection) => {
  selectedIncidents.value = selection
}

const handleRowClick = (row) => {
  // 双击查看详情
}

const handleSizeChange = (size) => {
  pageSize.value = size
  fetchIncidents()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchIncidents()
}

const openCreateIncidentDialog = () => {
  isEditMode.value = false
  resetIncidentForm()
  incidentForm.status = 'open'
  incidentForm.detectedTime = new Date().toISOString().slice(0, 16)
  createIncidentDialogVisible.value = true
}

const editIncident = async (incidentId) => {
  isEditMode.value = true
  
  // 获取事件详情
  const incident = incidents.value.find(inc => inc.id === incidentId)
  if (incident) {
    Object.keys(incidentForm).forEach(key => {
      if (incident[key] !== undefined) {
        incidentForm[key] = incident[key]
      }
    })
    
    createIncidentDialogVisible.value = true
  }
}

const viewIncident = async (incidentId) => {
  await fetchIncidentDetail(incidentId)
  newComment.value = ''
  activeTab.value = '0'
  incidentDetailDialogVisible.value = true
}

const submitIncidentForm = async () => {
  if (!incidentFormRef.value) return
  
  try {
    await incidentFormRef.value.validate()
    
    if (isEditMode.value) {
      await updateIncident({ ...incidentForm })
    } else {
      await createIncident({ ...incidentForm })
    }
    
    handleDialogClose()
  } catch (error) {
    // 表单验证失败，不需要特殊处理
  }
}

const handleDialogClose = () => {
  createIncidentDialogVisible.value = false
  resetIncidentForm()
  if (incidentFormRef.value) {
    incidentFormRef.value.clearValidate()
  }
}

const resetIncidentForm = () => {
  Object.keys(incidentForm).forEach(key => {
    incidentForm[key] = ''
  })
  incidentForm.priority = 'p3'
}

const closeIncidentDetail = () => {
  incidentDetailDialogVisible.value = false
  currentIncident.value = {}
}

const handleActionCommand = async (command, incidentId) => {
  switch (command) {
    case 'assign':
      openAssignDialog(incidentId)
      break
    case 'startProcess':
      await updateIncidentStatus(incidentId, 'processing')
      break
    case 'pauseProcess':
      await updateIncidentStatus(incidentId, 'open', '暂停处理')
      break
    case 'resolve':
      await updateIncidentStatus(incidentId, 'resolved')
      break
    case 'close':
      await updateIncidentStatus(incidentId, 'closed')
      break
    case 'delete':
      await confirmDeleteIncident(incidentId)
      break
  }
}

const handleDetailActionCommand = async (command, incident) => {
  switch (command) {
    case 'assign':
      openAssignDialog(incident.id)
      break
    case 'startProcess':
      await updateIncidentStatus(incident.id, 'processing')
      await fetchIncidentDetail(incident.id) // 刷新详情
      break
    case 'resolve':
      await updateIncidentStatus(incident.id, 'resolved')
      await fetchIncidentDetail(incident.id)
      break
    case 'close':
      await updateIncidentStatus(incident.id, 'closed')
      await fetchIncidentDetail(incident.id)
      break
    case 'addComment':
      openAddCommentDialog(incident.id)
      break
    case 'exportPDF':
      ElMessage.info('导出PDF功能开发中')
      break
  }
}

const handleHeaderCommand = (command) => {
  switch (command) {
    case 'exportIncidents':
      exportIncidents()
      break
    case 'importIncidents':
      ElMessage.info('导入事件功能开发中')
      break
    case 'batchClose':
      if (selectedIncidents.value.length === 0) {
        ElMessage.warning('请先选择事件')
        return
      }
      showBatchActionDialog('updateStatus', '批量关闭事件')
      batchActionForm.status = 'closed'
      break
  }
}

const refreshIncidents = () => {
  fetchIncidents()
}

const confirmDeleteIncident = async (incidentId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除此事件吗？此操作不可撤销。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteIncident(incidentId)
  } catch (error) {
    // 用户取消删除，不需要特殊处理
  }
}

const confirmBatchDeleteIncidents = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的${selectedIncidents.value.length}个事件吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const incidentIds = selectedIncidents.value.map(incident => incident.id)
    await batchDeleteIncidents(incidentIds)
    selectedIncidents.value = []
  } catch (error) {
    // 用户取消删除，不需要特殊处理
  }
}

const openAssignDialog = (incidentId) => {
  assignForm.assignee = ''
  assignForm.note = ''
  assignForm.incidentId = incidentId
  assignDialogVisible.value = true
}

const closeAssignDialog = () => {
  assignDialogVisible.value = false
  if (assignFormRef.value) {
    assignFormRef.value.clearValidate()
  }
}

const submitAssignForm = async () => {
  if (!assignFormRef.value) return
  
  try {
    await assignFormRef.value.validate()
    await assignIncident(assignForm.incidentId, assignForm.assignee, assignForm.note)
    
    // 如果正在查看该事件的详情，刷新详情
    if (incidentDetailDialogVisible.value && currentIncident.value.id === assignForm.incidentId) {
      await fetchIncidentDetail(assignForm.incidentId)
    }
    
    closeAssignDialog()
  } catch (error) {
    // 表单验证失败，不需要特殊处理
  }
}

const showBatchActionDialog = (type, title) => {
  resetBulkActionForm()
  batchActionType.value = type
  batchActionTitle.value = title
  batchActionDialogVisible.value = true
}

const resetBulkActionForm = () => {
  batchActionForm.assignee = ''
  batchActionForm.status = ''
  batchActionForm.severity = ''
  batchActionForm.note = ''
}

const closeBatchActionDialog = () => {
  batchActionDialogVisible.value = false
  if (batchActionFormRef.value) {
    batchActionFormRef.value.clearValidate()
  }
}

const submitBatchActionForm = async () => {
  if (!batchActionFormRef.value) return
  
  try {
    await batchActionFormRef.value.validate()
    const incidentIds = selectedIncidents.value.map(incident => incident.id)
    
    switch (batchActionType.value) {
      case 'assign':
        await batchAssignIncidents(incidentIds, batchActionForm.assignee, batchActionForm.note)
        break
      case 'updateStatus':
        await batchUpdateIncidentStatus(incidentIds, batchActionForm.status, batchActionForm.note)
        break
      case 'updateSeverity':
        await batchUpdateIncidentSeverity(incidentIds, batchActionForm.severity, batchActionForm.note)
        break
    }
    
    selectedIncidents.value = []
    closeBatchActionDialog()
  } catch (error) {
    // 表单验证失败，不需要特殊处理
  }
}

const openAddCommentDialog = (incidentId) => {
  commentForm.content = ''
  commentForm.attachments = []
  commentForm.incidentId = incidentId
  addCommentDialogVisible.value = true
}

const closeAddCommentDialog = () => {
  addCommentDialogVisible.value = false
  if (commentFormRef.value) {
    commentFormRef.value.clearValidate()
  }
}

const handleCommentFileUpload = (file) => {
  // 模拟文件上传
  commentForm.attachments.push(file)
  return false // 阻止自动上传
}

const submitCommentForm = async () => {
  if (!commentFormRef.value) return
  
  try {
    await commentFormRef.value.validate()
    await addCommentToIncident(commentForm.incidentId, commentForm.content, commentForm.attachments)
    
    // 如果正在查看该事件的详情，刷新详情
    if (incidentDetailDialogVisible.value && currentIncident.value.id === commentForm.incidentId) {
      await fetchIncidentDetail(commentForm.incidentId)
      activeTab.value = '5' // 切换到评论标签页
    }
    
    closeAddCommentDialog()
  } catch (error) {
    // 表单验证失败，不需要特殊处理
  }
}

const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  await addCommentToIncident(currentIncident.value.id, newComment.value)
  await fetchIncidentDetail(currentIncident.value.id)
  newComment.value = ''
}

// 生命周期钩子
onMounted(() => {
  fetchIncidents()
})
</script>

<!-- 样式导入 -->
<style>
@import '../assets/compliance-style.css';
</style>